#!/usr/bin/env python3
import sys, os
from argparse import ArgumentParser

parser = ArgumentParser(description='Converts binary file to mif file')

parser.add_argument('infile', help='Input binary file')
parser.add_argument('outfile', help='Output mif file')
parser.add_argument('-d', '--depth', help='Total memory depth (fill with zeros)', type=int, default=0)
parser.add_argument('-s', '--simple', help='Simple format (data only)', action="store_true", default=False)
args = parser.parse_args()

with open(args.infile, 'rb') as f:
    depth = os.path.getsize(args.infile)
    if args.depth > 0:
        if args.depth < depth:
            print ("ERROR: Input file is larger than the specified depth!")
            exit (-1)
        depth = args.depth

    with open(args.outfile, 'w') as fmif:
        if args.simple:
            count = 0
            buffer = f.read()
            for b in buffer:
                fmif.write('{0:08b}\n'.format(b))
                count += 1
            while count < depth:
                fmif.write('00000000')
                count += 1
        else:
            fmif.write('-- Automatically generated by bin2mif.py\n')
            fmif.write('-- Translated from ' + args.infile + '\n')
            fmif.write('DEPTH = {};\n'.format(depth))
            fmif.write('WIDTH = 8;\n')
            fmif.write('ADDRESS_RADIX = DEC;\n')
            fmif.write('DATA_RADIX = HEX;\n')
            fmif.write('CONTENT\n')
            fmif.write('BEGIN\n')

            count = 0
            buffer = f.read()
            for b in buffer:
                fmif.write('{0:<4}: {1:02x};\n'.format(count, b))
                count += 1
            if count < depth:
                fmif.write('[{0}..{1}] : 0;\n'.format(count, depth))
            fmif.write('END;\n')
